package com.heima.article.interceptor;

import com.heima.model.app.entity.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId) && !StringUtils.equals("0",userId)) {
            ApUser apUser = new ApUser();
            apUser.setId(Long.valueOf(userId));

            AppThreadLocalUtil.setUser(apUser);

        }

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清楚线程数据
        AppThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
